package com.shfl.controller;

import com.alibaba.fastjson.JSON;
import com.shfl.common.ApiResultHelper;
import com.shfl.common.ApiSimpleResultHelper;
import com.shfl.component.ToolServiceComponent;
import com.shfl.models.*;
import com.shfl.single.SingleUserInfo;
import com.shfl.stock.Stock;
import com.shfl.utils.AlertUtil;
import com.shfl.utils.MD5Util;
import com.shfl.utils.PropertiesUtil;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.util.Duration;

import java.io.IOException;
import java.net.URL;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IndexController implements Initializable {

    //公告
    @FXML
    private TextArea afficheText;


    // 登陆相关
    @FXML
    private TextField login_aliasName;

    @FXML
    private PasswordField login_password;

    @FXML
    private Button login_btn;

    // login end

    //注册相关
    @FXML
    private TextField signIn_aliasName;

    @FXML
    private TextField signIn_mail;

    @FXML
    private PasswordField signIn_passward;

    @FXML
    private PasswordField signIn_confirmPassword;

    @FXML
    private TextField signIn_verityCode;

    @FXML
    private Button signIn_seadCode;

    @FXML
    private Button signIn;

    // signIn end

    //重置密码相关
    @FXML
    private TextField reset_mail;
    @FXML
    private PasswordField reset_passward;
    @FXML
    private PasswordField reset_confirmPassword;
    @FXML
    private TextField reset_verityCode;
    @FXML
    private Button reset_seadCode;
    @FXML
    private Button reset;


    // reset end
    @Override
    public void initialize(URL location, ResourceBundle resources) {


        //获取公告
        Stock.executor.execute(() -> {
            String executorText = "";
            try {
                executorText = PropertiesUtil.getProperty(Stock.proUrl, "project.affiche");
            } catch (IOException e) {
                e.printStackTrace();
            }
            this.afficheText.setText(executorText + this.getAffiche());
        });
//        new Thread(() -> {
//            this.afficheText.setText(this.getAffiche());
//        }, "affiche").start();

        //点击登陆按钮
        this.login_btn.setOnAction(event -> {
            login_btn.setDisable(true);
            login(login_aliasName.getText(), login_password.getText());
            waitTime(login_btn, 5);
        });

        //发送注册邮件
        this.signIn_seadCode.setOnAction(event -> {
            signIn_seadCode.setDisable(true);
            seadCode(signIn_mail.getText(), 1);
            waitTime(signIn_seadCode, 60);
        });

        //注册账户
        this.signIn.setOnAction(event -> {
            signIn.setDisable(true);
            signIn(signIn_aliasName.getText(), signIn_mail.getText(), signIn_passward.getText(), signIn_confirmPassword.getText(), signIn_verityCode.getText());
            waitTime(signIn, 5);
        });

        //发送重置密码邮件
        this.reset_seadCode.setOnAction(event -> {
            reset_seadCode.setDisable(true);
            seadCode(reset_mail.getText(), 2);
            waitTime(reset_seadCode, 60);
        });

        //重置密码
        this.reset.setOnAction(event -> {
            reset.setDisable(true);
            ResetInfo info = new ResetInfo();
            info.setMailAddess(reset_mail.getText());
            info.setPassword(reset_passward.getText());
            info.setVerifyCode(reset_verityCode.getText());
            reset(info, reset_confirmPassword.getText());
            waitTime(reset, 5);
        });
    }


    /**
     * 获取公告
     *
     * @return
     */
    protected String getAffiche() {
        ApiSimpleResultHelper result = new ToolServiceComponent().affiche();
        if ("0000".equals(result.getResCode())) {
            SingleUserInfo.getSingleUserInfo().setAffiche(JSON.parseObject(JSON.toJSONString(result.getData()), Map.class).get("affiche").toString());
            if (SingleUserInfo.getSingleUserInfo().getAffiche() != null && SingleUserInfo.getSingleUserInfo().getAffiche().contains("\\n")) {
                SingleUserInfo.getSingleUserInfo().setAffiche(SingleUserInfo.getSingleUserInfo().getAffiche().replaceAll("\\\\n", "\n"));
            }
            return SingleUserInfo.getSingleUserInfo().getAffiche();
        } else {
            return result.getResDesc();
        }
    }


    /**
     * 发送邮件
     *
     * @param mailAddess
     * @param sendType
     */
    protected void seadCode(String mailAddess, Integer sendType) {
        //校验邮箱
        if (mailAddess.isEmpty()) {
            AlertUtil.f_alert_informationDialog("邮箱不能为空!");
            return;
        }
        if (!isEmail(mailAddess)) {
            AlertUtil.f_alert_informationDialog("请检查邮箱地址!");
            return;
        }
        SendMailInfo info = new SendMailInfo();
        info.setMailAddess(mailAddess);
        info.setSendType(sendType);
        ApiResultHelper result = new ToolServiceComponent().seadCode(info);
        if (!"0000".equals(result.getResCode())) {
            AlertUtil.f_alert_informationDialog(result.getResDesc());
            return;
        }
        AlertUtil.f_alert_informationDialog("请查看验证码!");
    }

    /**
     * 登陆
     *
     * @param aliasName
     * @param password
     */
    protected void login(String aliasName, String password) {
        if (aliasName.isEmpty() || password.isEmpty()) {
            AlertUtil.f_alert_informationDialog("用户名或密码不能为空!");
            return;
        }
        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setAliasName(aliasName);
        loginInfo.setPassword(MD5Util.encrypt(password));
        ApiSimpleResultHelper result = new ToolServiceComponent().login(loginInfo);
        if (!"0000".equals(result.getResCode())) {
            AlertUtil.f_alert_informationDialog(result.getResDesc());
            return;
        }
        SingleUserInfo singleUserInfo = SingleUserInfo.getSingleUserInfo();
        singleUserInfo.setTokenInfo(JSON.parseObject(JSON.toJSONString(result.getData()), TokenInfo.class));
        Stock.INDEX_STAGE.setScene(new Scene(Stock.parent2(), Stock.width, Stock.height));
//        try {
//            Stock.convertImageMain.showWindow();
//            Stock.INDEX_STAGE.hide();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    /**
     * 注册
     *
     * @param signIn_aliasName
     * @param signIn_mail
     * @param signIn_passward
     * @param signIn_confirmPassword
     * @param signIn_verityCode
     */
    protected void signIn(String signIn_aliasName, String signIn_mail, String signIn_passward, String signIn_confirmPassword, String signIn_verityCode) {
        if (signIn_aliasName.isEmpty() || signIn_mail.isEmpty() || signIn_passward.isEmpty() || signIn_confirmPassword.isEmpty() || signIn_verityCode.isEmpty()) {
            AlertUtil.f_alert_informationDialog("请填完基本信息!");
            return;
        }
        if (!signIn_passward.equals(signIn_confirmPassword)) {
            AlertUtil.f_alert_informationDialog("两次密码输入不同!");
            return;
        }
        if (!isEmail(signIn_mail)) {
            AlertUtil.f_alert_informationDialog("请检查邮箱地址!");
            return;
        }
        SignInInfo info = new SignInInfo();
        info.setAliasName(signIn_aliasName);
        info.setMailAddess(signIn_mail);
        info.setPassword(MD5Util.encrypt(signIn_passward));
        info.setVerifyCode(signIn_verityCode);
        ApiResultHelper result = new ToolServiceComponent().signIn(info);
        if (!"0000".equals(result.getResCode())) {
            AlertUtil.f_alert_informationDialog(result.getResDesc());
            return;
        }
        AlertUtil.f_alert_informationDialog("注册成功!请登录!");
    }

    /**
     * 重置密码
     *
     * @param info
     */
    protected void reset(ResetInfo info, String reset_confirmPassword) {
        if (info.getMailAddess().isEmpty() || info.getPassword().isEmpty() || reset_confirmPassword.isEmpty()) {
            AlertUtil.f_alert_informationDialog("请填完基本信息!");
            return;
        }
        if (!info.getPassword().equals(reset_confirmPassword)) {
            AlertUtil.f_alert_informationDialog("两次密码输入不同!");
            return;
        }
        if (!isEmail(info.getMailAddess())) {
            AlertUtil.f_alert_informationDialog("请检查邮箱地址!");
            return;
        }
        info.setPassword(MD5Util.encrypt(info.getPassword()));
        ApiResultHelper result = new ToolServiceComponent().reset(info);
        if (!"0000".equals(result.getResCode())) {
            AlertUtil.f_alert_informationDialog(result.getResDesc());
            return;
        }
        AlertUtil.f_alert_informationDialog("重置密码成功!请登录!");
    }


    /**
     * 等待时长
     *
     * @param button 按钮
     * @param val    秒
     */
    protected <T extends Button> void waitTime(T button, Integer val) {
        final Timeline animation = new Timeline(
                new KeyFrame(Duration.seconds(val),
                        actionEvent -> button.setDisable(false)));
        animation.setCycleCount(1);
        animation.play();
    }


    //判断Email合法性
    public static boolean isEmail(String email) {
        if (email == null)
            return false;
        String rule = "[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?";
        Pattern pattern;
        Matcher matcher;
        pattern = Pattern.compile(rule);
        matcher = pattern.matcher(email);
        if (matcher.matches())
            return true;
        else
            return false;
    }

}
